<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/12/10
 * Time: 20:30
 */
class Prizeeveryday extends BZ_Controller
{
    public function _init()
    {
        $this->load->library('pagination');
        $this->load->helper('common');
        $this->load->model('prize_every_day_model', 'prize_every_day');
        $this->load->model('lottery_prize_model', 'lottery_prize');
        $this->load->model('user_model', 'user');
    }

    public function index()
    {
        $prizeId = $this->input->get('prize_id');
        if ($this->validateParam($prizeId)){
            $this->error('lotteryprize/index/', getLotteryUrl(2, true), '奖品编号不存在');
        }
        $result = $this->lottery_prize->findOnePrize($prizeId);
        if ($result->num_rows() == 0) {
            $this->error('lotteryprize/index/', getLotteryUrl(2, true), '奖品不存在');
        }
        $prize = $result->row();
        $prefs = array (
            'show_next_prev' => true,
            'next_prev_url' => base_url('prizeeveryday/index?'. getLotteryUrl(2))
        );
        $this->load->library('calendar',$prefs);
        $year  = $this->input->get('year') ? $this->input->get('year') : date('Y');
        $month = $this->input->get('month') ? $this->input->get('month') : date('m');
        $generate = $this->getCalendarData($year, $month, $prize);
        $data['generate'] = $this->calendar->generate($year, $month, $generate);
        $data['prize'] = $prize;
        $this->load->view('prizeEveryDay/index',$data);
    }

    /**
     * 日历
     */
    public function getCalendarData($year, $month, $prize){
        $status = array(1 => '可抽奖', 2 => '不可抽奖');
        $getData = $this->input->get();
        $getData['date'] = $year.'-'.$month;
        $getData['prize_id'] = $prize->prize_id;
        $result = $this->prize_every_day->find($getData);
        //$dayNum = cal_days_in_month(CAL_GREGORIAN, $month, $year); 由于服务不支持该函数  so
        $dayNum = $this->days_in_month($month,$year);
        $generate = array();
        if ($result->num_rows() > 0){
            $prizeDay = $result->result();
            for($i=1;$i<=$dayNum;$i++){
                $day = $i;
                if (strlen($i) == 1){
                    $day = '0'.$i;
                }
                $date = $year.'-'.$month.'-'.$day;
                $flag = true;
                foreach ($prizeDay as $key=>$value){
                    if ($i == $value->day) {
                        $flag = false;
                        $winnersUser = ($value->winners_user) ? implode(' ', array_keys(json_decode($value->winners_user, true)))  : '';
                        $generate[$i] = '<ul class="td-color popovers" data-date="'.$date.'" data-placement="bottom" data-trigger="hover" data-original-title="指定中奖者" data-content="'. $winnersUser.'"><li class="day">'.$i.'</li>';
                        $generate[$i] .= '<li class="shou">数量：'. $value->quantity. '  剩余数量：'. $value->surplus_quantity.'</li>
                            <li class="shou">中奖概率：'. $value->probability.'</li>
                            <li class="shou">指定中奖者：'. ($winnersUser ? '查看' : '--'). '</li>
                            <li class="shou">中奖时间段：'. $value->start_time. '--'. $value->end_time.'</li>
                            <li class="shou zao">上下架：'. $status[$value->status].'</li>';
                        unset($prizeDay[$key]);
                        break;
                    }
                }
                if ($flag){
                    $generate[$i] = '<ul class="td-color" data-date="'.$date.'"><li class="day">'.$i.'</li>';
                    $generate[$i] .= '<li class="shou">数量：---</li>
                                      <li class="shou jie">剩余数量：---</li>
                                      <li class="shou">中奖概率：---</li>
                                      <li class="shou zao">上下架：---</li>';
                }
            }
        } else {
            for($i=1;$i<=$dayNum;$i++){
                $day = $i;
                if (strlen($i) == 1){
                    $day = '0'.$i;
                }
                $date = $year.'-'.$month.'-'.$day;
                $generate[$i] = '<ul class="td-color" data-date="'.$date.'"><li class="day">'.$i.'</li>';
                $generate[$i] .= '<li class="shou">数量：---</li>
                                  <li class="shou jie">剩余数量：---</li>
                                  <li class="shou">中奖概率：---</li>
                                  <li class="shou zao">上下架：---</li>';
                $generate[$i] .= '</ul>';
            }
        }
        return $generate;
    }

    public function addBatchPost()
    {
        $postData = $this->validate();

        $this->db->trans_start();
        $updateData = array();
        $result = $this->prize_every_day->find(array('date' => $postData['date'], 'prize_id'=> $postData['prize_id']));
        $timeSlot = array();
        if ($postData['start_time'] && $postData['end_time']) {
            foreach($postData['date'] as $value) {
                $timeSlot[$value] = $this->randomTime($value. ' '. $postData['start_time'], $value. ' '. $postData['end_time'], $postData['quantity']);
            }
        }
        $date = array_flip($postData['date']);
        if ($result->num_rows() > 0) {
            foreach ($result->result() as $key=>$value) {
                if (array_key_exists($value->date, $date)) {
                    $updateData[$key]['date'] = $value->date;
                    $updateData[$key]['day_id'] = $value->day_id;
                    $updateData[$key]['time_slot'] = isset($timeSlot[$value->date]) ? $timeSlot[$value->date] : '';
                    unset($date[$value->date]);
                }
            }
            if ( !empty($updateData)) {
                $this->prize_every_day->updateBatch($updateData, $postData);
            }
        }
        if ( !empty($date)) {
            $insertId = $this->prize_every_day->insertBatch($postData, $date, $timeSlot);
        }
        $this->db->trans_complete();

        $url = parse_url($_SERVER['HTTP_REFERER']);
        if ($this->db->trans_status() === FALSE) {
            $this->error('prizeeveryday/index/', '?'. $url['query'], '内部操作失败');
        } else {
            $this->setActivityPrizeCache($postData['lottery_id']); //设置缓存
            $this->success('prizeeveryday/index/', '?'. $url['query'], '操作成功');
        }
    }

    public function validate()
    {
        $postData = $this->input->post();
        $error = array();
        if ($this->validateParam($postData['prize_id'])){
            $error[] = '奖品编号不存在';
        }

        $result = $this->lottery_prize->findOnePrize($postData['prize_id']);
        if ($result->num_rows() == 0) {
            $error[] = '奖品不存在';
        }

        if ($this->validateParam($postData['date'])){
            $error[] = '日期不可为空';
        }

        $date = array_map('valiDate', explode(',', trim($postData['date'], ',')));
        if (in_array(false, $date)) {
            $error[] = '日期格式不正确！';
        }

        $postData['date'] = $date;

        if (!is_numeric($postData['quantity']) || $postData['quantity'] < 0 || $postData['quantity'] >= 16777215) {
            $error[] = '数量只能为正整数，不可超出范围';
        }
        if ( !empty($postData['probability']) && ( !is_numeric($postData['probability']) || $postData['probability'] < 0 || $postData['probability'] > 100)) {
            $error[] = '概率只能为正整数，范围1-100';
        }

        if ( !empty($postData['winners_user'])) {
            $winner = array_filter(explode(',', $postData['winners_user']));
            if ( !empty($winner)) {
                $winners = json_encode(array_fill_keys($winner, 0));
                // $winners = $this->valiUsername($winner);
                // if ( isset($winners['error'])) {
                //     $error[] = $winners['error'];
                // }
                $postData['winners_user'] = $winners;
            }
        }
        if ( !empty($postData['start_time']) && !checkTimeHm($postData['start_time'])) {
            $error[] = '中奖起始时间：格式错误';
        }

        if ( !empty($postData['end_time']) && !checkTimeHm($postData['end_time'])) {
            $error[] = '中奖结束时间：格式错误';
        }

        if ( !empty($postData['start_time']) && !empty($postData['end_time']) && strtotime($postData['start_time']) >= strtotime($postData['end_time'])) {
            $error[] = '中奖起始时间不可大于结束时间';
        }

        if ( !empty($error)) {
            $url = parse_url($_SERVER['HTTP_REFERER']);
            $this->error('prizeeveryday/index/', '?'.$url['query'], $error);
        }
        return $postData;
    }

    private function days_in_month($month, $year) {
        return $month == 2 ? ($year % 4 ? 28 : ($year % 100 ? 29 : ($year % 400 ? 28 : 29))) : (($month - 1) % 7 % 2 ? 30 : 31);
    }

    /**
     * 缓存今天的剩余数量
     */
    private function setActivityPrizeCache($lotteryId)
    {
        $activityPrize = $this->lottery_prize->findPrizes(array('lottery_id' => $lotteryId));
        if ($activityPrize->num_rows() == 0) {
            $this->cache->memcached->delete('activityPrize'. $lotteryId); //删除缓存
        }
        $activityPrize = $activityPrize->result();
        $expires = strtotime(date('Y-m-d 23:59:59')) - time();
        $this->cache->memcached->save('activityPrize'. $lotteryId, $activityPrize, $expires); //缓存今天
    }

    /**
     * 生成随机时间
     */
    private function randomTime($startTime, $endTime, $count)
    {
        $time = array();
        $count = $count >= 10 ? 10 : $count;
        for ($i=0; $i < $count; $i++) {
            $time[mt_rand(strtotime($startTime), strtotime($endTime))] = 0;
        }
        ksort($time);
        return json_encode($time);
    }

     /**
     * 验证指定用户是否存在
     */
    private function valiUsername($username)
    {
        $result = $this->user->findByIds(array('user_name' => $username));
        if ($result->num_rows() == 0) {
            return array('error' => '指定用户不存在');
        }
        $data = array();
        foreach ($result->result() as $value) {
            $data[] = $value->user_name;
        }
        $diff = array_diff($username, $data);
        if ( !empty($diff)) {
            return array('error' => '指定用户('. implode(',', $diff). ')不存在');
        }
        return json_encode(array_fill_keys($data, 0));
    }
}